package com.lqm.web.config;


import com.lqm.web.converter.DateConverter;
import com.lqm.web.interceptor.AdminInterceptor;
import com.lqm.web.interceptor.HomeInterceptor;
import com.lqm.web.interceptor.TestInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ConversionServiceFactoryBean;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

/**
 * @program: CrowdFunding
 * @description SpringMVC 开启拦截器配置，配置拦截的URL
 * @author: lqm
 * @create: 2018-12-03 21:37
 */
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Bean
    public HandlerInterceptor getAdminInterceptor(){
        return new AdminInterceptor();
    }

    @Bean
    public HandlerInterceptor getHomeInterceptor(){
        return new HomeInterceptor();
    }

    @Bean
    public HandlerInterceptor getTestInterceptor(){
        return new TestInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // addPathPatterns 用于添加拦截规则, 这里假设拦截 /url 后面的全部链接
        // excludePathPatterns 用户排除拦截
        ArrayList<String> list = new ArrayList<>();
        list.add("/admin/index.html");
        list.add("/admin/layui/**");
        list.add("/admin/getAdminUser");
        list.add("/admin/login");
        list.add("/admin/json/**");
        registry.addInterceptor(getAdminInterceptor())
                .addPathPatterns("/admin/**")
                .excludePathPatterns(list);

        ArrayList<String> homeList = new ArrayList<>();
        homeList.add("/home/login.html");
        homeList.add("/home/sign.html");
        ArrayList<String> homeArrayList = new ArrayList<>();
        homeArrayList.add("/home/**.html");
        registry.addInterceptor(getHomeInterceptor())
                .addPathPatterns(homeArrayList)
                .excludePathPatterns(homeList);

    }


    /**
     * 配置全局字符串转时间的转换器
     * @param dateConverter
     * @return
     */

    @Bean
    @Autowired
    public ConversionService getConversionService(DateConverter dateConverter){
        ConversionServiceFactoryBean factoryBean = new ConversionServiceFactoryBean();

        Set<Converter> converters = new HashSet<Converter>();

        converters.add(dateConverter);

        factoryBean.setConverters(converters);

        return factoryBean.getObject();
    }


}
